<template>
  <div class="register-container">
    <div class="logo-wrapper">logo</div>
    <div class="login-form">
      <!-- <div class="user-name">
        <cube-input v-model="firstName" type="text" placeholder="First Name">
        </cube-input>
        <cube-input v-model="lastName" type="text" placeholder="Last Name">
        </cube-input>
      </div>-->
      <cube-input v-model="loginAccount" type="text" placeholder="Username" />
      <cube-input v-model="email" type="text" placeholder="Email" />
      <div class="wrapper">
        <cube-input v-model="authCode" type="text" placeholder="Verification code" />
        <cube-button @click="onGetAuthCode" :disabled="authBtn" light>{{ authText }}</cube-button>
      </div>
      <cube-input v-model="mobilePhone" type="text" placeholder="Phone Number"></cube-input>
      <cube-input v-model="password" type="password" placeholder="Password" :eye="eye"></cube-input>
      <cube-input v-model="confirmPassword" type="password" placeholder="Repeat password" :eye="eye"></cube-input>
      <div class="actions">
        <cube-button primary @click="onRegister">Sign up</cube-button>
        <cube-button light @click="onLoginClicked">Log in</cube-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { Api, Login } from "@/api";
import { VerificationCodeVo, CustomUserLoginInfo } from "@/api/bean";
declare const $Vue: Vue;
const COUNT_DOWW = 60;

@Component({
  components: {}
})
export default class Register extends Vue {
  private loginAccount: string = "";
  private email: string = "";
  private authCode: string = "";
  private password: string = "";
  private mobilePhone: string = "";
  private confirmPassword: string = "";
  private authBtn: boolean = false;
  private authText: string = "Get code";

  private countDown: number = COUNT_DOWW;
  private interval: any = null;


  private eye = {
    open: false,
    reverse: false
  };

  private invitation: any = '';

  protected mounted() {
    $Vue.$emit("title", {
      message: "Register"
    });

    this.checkInvitation();
  }

  private onLoginClicked() {
    this.$router.push({
      name: "Login"
    });
  }

  private checkInvitation() {
    let invitation: any = this.$route.query.invitation;
    if  (invitation) {
      this.invitation = invitation.replace(' ', '+');
      localStorage.setItem('invitation', 'invitation');
    }
  }

  private onGetAuthCode() {
    if (this.email === "") {
      return this.$createDialog({
        type: "alert",
        title: "Attention",
        content: "Please enter your email address!",
        icon: "cubeic-alert",
        confirmBtn: {
          text: "OK",
          active: true,
          disabled: false,
          href: "javascript:;"
        }
      }).show();
    }

    let reg = /^[A-Za-z0-9\u4e00-\u9fa5\.]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
    if (this.email.match(reg)) {
      this.getAuthCode();
      this.authBtn = true;
      this.interval = setInterval(() => {
        this.authText = `resend after ${this.countDown}s`;
        this.countDown--;
        if (this.countDown <= 0) {
          this.authBtn = false;
          this.authText = "Get code";
          this.countDown = COUNT_DOWW;
          clearInterval(this.interval);
        }
      }, 1000);
    } else {
      return this.$createDialog({
        type: "alert",
        title: "Attention",
        content: "Invalid email address!",
        icon: "cubeic-alert",
        confirmBtn: {
          text: "OK",
          active: true,
          disabled: false,
          href: "javascript:;"
        }
      }).show();
    }
  }

  private onRegister() {
    // this.validate();
    this.handleRegister();
  }

  private validate() {
    if (this.confirmPassword !== this.password) {
      return this.$createToast({
        txt: 'You should enter the same password',
        type: "warn",
        time: 3000,
      }).show();
    }
    this.checkLoginAccount();
    // this.handleRegister();
  }

  private handleSuccess() {
     this.$createToast({
        txt: 'Registration success',
        type: "correct",
        time: 3000,
      }).show();
    this.$router.push({
      name: "Login"
    });
  }

  /**
   * 获取验证码
   */
  private async getAuthCode() {
    const params: VerificationCodeVo = {
      targetAddr: this.email,
      userType: 1,
    };

    const { data } = await Login.getAuthCode.r(params);
    console.log("getAuthCode", data);
    if (data.result === 0) {
      this.$createToast({
        txt: 'Code has been sended to you email box',
        type: "correct",
        time: 3000,
      }).show();
    } else {
      this.$createDialog({
        type: "alert",
        title: "Attention",
        content: "Incorrect verification code!",
        icon: "cubeic-alert",
        confirmBtn: {
          text: "OK",
          active: true,
          disabled: false,
          href: "javascript:;"
        }
      }).show();
    }
  }

  /**
   * 验证
   */
  private async validateAuthCode() {
    const params: VerificationCodeVo = {
      targetAddr: this.email,
      code: this.authCode,
      userType: 1,
    };

    const { data } = await Login.validateAuthCode.r(params);
    console.log("register", data);
    if (data.result === 0) {
      this.handleRegister();
    } else {
      this.$createDialog({
        type: "alert",
        title: "Attention",
        content: data.message,
        icon: "cubeic-alert",
        confirmBtn: {
          text: "OK",
          active: true,
          disabled: false,
          href: "javascript:;"
        }
      }).show();
    }
  }

  /**
   * 注册
   */
  private async handleRegister() {
    // userType 1 为买家
    let params: any = {
      userType: 1,
      username: this.loginAccount,
      loginAccount: this.loginAccount,
      email: this.email,
      password: this.password,
      mobilePhone: this.mobilePhone,
      confirmedPassword: this.password,
    };
    if (this.invitation) {
      params.pInvitationCode = this.invitation;
    }
    const { data } = await Login.handleRegister.r(params);
    console.log("handleRegister", data);
    if (data.result === 0) {
      this.handleSuccess();
    } else {
      this.$createDialog({
        type: "alert",
        title: "Attention",
        content: data.message,
        icon: "cubeic-alert",
        confirmBtn: {
          text: "OK",
          active: true,
          disabled: false,
          href: "javascript:;"
        }
      }).show();
    }
  }

    /**
   * 验证
   */
  private async checkLoginAccount() {
    const params: any = {
      loginAccount: this.loginAccount,
      userType: 1,
    }; // 1为买家
    const { data } = await Login.checkLoginAccount.r(params);
    console.log('checkLoginAccount', data);
    if (data.result === 0) {
      console.log(data.data)
      // if (data.data) {
        // this.handleRegister();
        this.validateAuthCode();
      // }
    } else {
      $Vue.$emit('snackbar', {
        message: 'This Username has been used',
      });
    }
  }
}
</script>

<style lang="less" scoped>
.cube-input {
  width: 100% !important;
}
.register-container {
  display: flex;
  flex-direction: column;
  padding: 3% 14%;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  .logo-wrapper {
    height: 2%;
    flex-basis: 5%;
  }
  .login-form {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    // height: 14rem;
    .user-name {
      display: flex;
      justify-content: space-between;
    }
  }

  .actions {
    width: 100%;
    padding-top: 1.2rem;
  }

  .wrapper {
    display: flex;
  }

  .cube-input {
    margin: 2px!important;
        height: 3rem;
  }
}
</style>
